package com.leador.batch;

import android.util.Log;

import com.leador.assist.DataQueueManager;
import com.leador.batch.db.DatabaseManager;
import com.leador.batch.db.PackageUtils;
import com.leador.http.HttpManager;
import com.leador.listener.OnPointListener;
import com.leador.module.AppInfo;
import com.leador.module.ILocation;
import com.leador.service.LBSTraceService;
import com.leador.utils.CsvWriter;

import java.io.File;
import java.util.Deque;
import java.util.List;

/**
 * Created by liuha on 2016/9/18.
 */
public class SyncHttpThread extends Thread{
    private LBSTraceService lbsTraceService;
    private OnPointListener onPointListener;
    public  SyncHttpThread(LBSTraceService lbsTraceService,OnPointListener onPointListener){
        this.lbsTraceService = lbsTraceService;
        this.onPointListener = onPointListener;
    }
    @Override
    public void run() {
        super.run();
        if(lbsTraceService == null){
            return;
        }
        DatabaseManager.getInstance(lbsTraceService.getContext()).getData();
        Deque deque = DataQueueManager.getInstance().getiLocations();
        if(deque.size() > 0){
            try {
                pitchDoc(deque);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    File file = null;
    private void pitchDoc(Deque deque) throws Exception{
        String serviceId = String.valueOf(AppInfo.serviceId);
        String entityName = String.valueOf(AppInfo.entityName);
        String[] headJson = {"longitude","latitude","loc_time","coord_type"};
        String path  = PackageUtils.getCacheDirectory()+"/write"+".csv";
        CsvWriter csv = new CsvWriter(path);
        file = new File(path);
        if(file.exists()){
            file.delete();
        }
        file.createNewFile();
        csv.writeRecord(headJson,false);
        while (deque.size() > 0){
            Object obj = deque.poll();
            ILocation iLocation = (ILocation) obj;
            String[] str = new String[4];
            str[0] = iLocation.getLongitude();
            str[1] = iLocation.getLatitude();
            str[2] = iLocation.getLoc_time();
            str[3] = iLocation.getCoord_type();
            csv.writeRecord(str,false);
            DataQueueManager.getInstance().iLocationTemp.add(obj);
        }
        if(file.exists()){
            HttpManager.getInstance().addTracks(lbsTraceService.getContext(),serviceId,entityName,file,onPointListener);
        }
        csv.close();
    }

     //TODO 批量上报时候自定义字段上报
//    public String custom(ILocation iLocation){
//        String custom = iLocation.getExtend1();
//        if(custom != null && !custom.equals("")){
//            String[] strArray = custom.split(";");
//            for(String str : strArray){
//                String[] single = str.split("-");
//                sb.append("&"+single[0]).append("=").append(single[1]);
//            }
//        }
//    }

}
